package com.uxsino.simo.query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uxsino.commons.utils.config.PropElement;
import com.uxsino.reactorq.model.IndicatorValue;
import com.uxsino.simo.indicator.ListIndicator;
import com.uxsino.simo.indicator.expression.ExprEvaluator;
import com.uxsino.simo.utils.ConfigLoadingContext;

public class ScriptQueryCombine extends QueryCombine<ListIndicator, List<Map<String, Object>>> {

    public ScriptQueryCombine(ListIndicator resultIndicator) {
        super(resultIndicator);
    }

    @SuppressWarnings("unused")
    private static Logger logger = LoggerFactory.getLogger(ScriptQueryCombine.class);
    // @ConfigProp(name = "formula", required = true, subElement = true)
    // protected String formula;

    @Override
    public List<Map<String, Object>> apply(QueryContext ctxt, List<IndicatorValue> lists) {

        if (lists.size() == 0)
            return new ArrayList<Map<String, Object>>();

        ExprEvaluator ev = ctxt.getExprEvaluator(lists.get(0).entityId);
        Map<String, Object> variables = new HashMap<>();

        List<Map<String, Object>> subQueryResults = new ArrayList<>();
        List<Map<String, Object>> qResults = new ArrayList<>();
        for (IndicatorValue v : lists) {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> lv = (List<Map<String, Object>>) v.value;
            subQueryResults.addAll(lv);
        }

        for (Map<String, Object> listValue : subQueryResults) {
            for (Map.Entry<String, Object> entry : listValue.entrySet()) {
                variables.put(entry.getKey(), entry.getValue());
            }
        }
        qResults.add(variables);

        ev.evalExprFields(ctxt.getDepo().getIndicatorNamespace().getIndicator(lists.get(0).indicatorName), qResults);

        return qResults;
    }

    @Override
    public void loadProp(PropElement eCombine, ConfigLoadingContext lctxt) {

    }

    @Override
    public boolean isCustom() {
        return false;
    }
}
